package com.ex.service;

import com.ex.common.ResultData;
import com.ex.common.StringUtil;
import com.ex.constants.Constants;
import com.ex.dao.AccountJap;
import com.ex.entity.Account;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * <h1>账户的业务逻辑层</h1>
 *
 * @author longdeng
 * @Date 2019/10/7 19:39
 */
@Slf4j
@Service
public class AccountService {

    @Autowired
    private AccountJap accountJap;

    public Account findByUsername(String username) {
        return accountJap.findByUsername(username);
    }

    /**
     * 用户注册
     *
     * @param map 用户注册信息
     * @return
     */
    public ResultData register(Map<String, String> map) {
        Account account = regInstance(map);
        Account save = accountJap.save(account);
        if (!Objects.isNull(save)) {
            return ResultData.success(Constants.ADD_SUCCESS.getDesc());
        }
        return ResultData.error(Constants.ADD_FAILD.getDesc());

    }

    /**
     * 构建账户注册用户信息
     *
     * @param map 用户信息集合
     * @return {@link Account}
     */
    public Account regInstance(Map<String, String> map) {
        String username = map.get("username");
        String password = map.get("password");
        String salt = StringUtil.randomStrUppercase(6, false);
        try {
            // 存入数据库的密码信息
            String dataPassword = StringUtil.MD5(password, salt);
            map.put("password", dataPassword);
        } catch (NoSuchAlgorithmException e) {
            log.info("{} - {} - {} - {} ", new Date(), this.getClass().getName(), "regInstance", "生成密码失败");
            e.printStackTrace();
        }
        Account account = new Account();
        account.setUsername(username);
        account.setPassword(map.get("password"));
        account.setSalt(salt);
        account.setAccountNo(StringUtil.randomStrUppercase(10, true));
        return account;
    }

    /**
     * 账户登录
     *
     * @param map 用户信息集合
     * @return
     */
    public ResultData login(Map<String, String> map) {

        return null;

    }
}
